<!-- 巡护记录 -->
<script setup>
import { reactive, toRefs, ref, onMounted, createVNode, render, onBeforeUnmount } from 'vue';
import {
  ElButton,
  ElInput,
  ElOption,
  ElSelect,
  ElTable,
  ElTableColumn,
  ElDatePicker,
  ElPagination,
} from 'element-plus';
import * as turf from '@turf/turf';
import dayjs from 'dayjs';
import mitt from '@/common/common-helper';
import PATROL_ICON from '../../../assets/images/icon/人员.png';
import CommonMapPopup from '../common/CommonMapPopup.vue';
import {
  GET_MAPBOX_MAP,
  REMOVE_LAYER,
  REMOVE_MAP_IMG,
  CLEAR_POPUP_MAP,
  POINT_MARKER,
  MAP_UPDATE_REALTIME_LINE,
  MAP_POPUP,
} from '../common/common-map-fun';
import { layerGroupId } from '../common/common-map-info';

const props = defineProps({
  btnChecked: String,
  lookState: Boolean,
});
const { btnChecked, lookState } = toRefs(props);
const emit = defineEmits(['handleRecordLookItem']);

let map = null;
let vNodePopup = null;

const total = ref(1);
const patrolOption = ref([
  {
    id: '56235666618662912',
    roleName: '研发',
  },
  {
    id: '55105873600720896',
    roleName: '监测部门',
  },
  {
    id: '55102663615983616',
    roleName: '三图信息技术',
  },
  {
    id: '54791447039328256',
    roleName: '测试部门',
  },
  {
    id: '52564990628151296',
    roleName: '数字孪生',
  },
  {
    id: '52513707154161664',
    roleName: '积木科技',
  },
  {
    id: '52511870262919168',
    roleName: '西安市三图科技有限',
  },
  {
    id: '52219207487758336',
    roleName: '图灵普惠',
  },
  {
    id: '47091773642629120',
    roleName: '林业站',
  },
]);
const tableList = ref([]);

const currentRow = ref();
const singleTableRef = ref();
const lookItem = ref({});
const userItemLayer = reactive({
  startPoint: {},
  endPoint: {},
  line: [],
});

const selectParams = reactive({
  startDate: '',
  endDate: '',
  username: '',
  deptName: '全部',
  deptId: '',
  pageNum: 1,
  pageSize: 20,
  dateRange: '',
});

const page = () => {
  selectParams.pageNum = 1;
  selectParams.pageSize = 20;
};

/**
 *@description: 获取通讯信息
 */
mitt.on('handleItemGJ', (val) => {
  if (val) {
    singleTableRef?.value?.setCurrentRow();
    currentRow.value = '';
    CLEAR_MAP_LAYER();
  }
});

onMounted(() => {
  if (btnChecked.value == '巡护记录') {
    map = GET_MAPBOX_MAP();

    recordPageListApi(selectParams);
  }
});

const handleSizeChange = (val) => {
  selectParams.pageSize = val;
  recordPageListApi(selectParams);
};

const handleCurrentChange = (val) => {
  selectParams.pageNum = val;
  recordPageListApi(selectParams);
};

const onChangeDataRange = (e) => {
  if (e) {
    selectParams.startDate = dayjs(e[0]).format('YYYY-MM-DD');
    selectParams.endDate = dayjs(e[1]).format('YYYY-MM-DD');
  } else {
    selectParams.startDate = '';
    selectParams.endDate = '';
  }
};

const onChangeOption = (e) => {
  selectParams.deptId = e;

  if (e == '') {
    selectParams.deptName = '全部';
  }
};

const handleSelectQuery = () => {
  page();
  CLEAR_MAP_LAYER();
  singleTableRef.value.setCurrentRow();
  currentRow.value = '';
  mitt.emit('handleItemGJAll', true);
  recordPageListApi(selectParams);
};

const handleRowClick = (val) => {
  CLEAR_MAP_LAYER();
  mitt.emit('handleItemGJAll_', true);

  if (lookItem.value.id !== val.id) {
    mitt.emit('handleItemGJAll', true);
  }

  if (currentRow.value?.id == val.id) {
    singleTableRef.value.setCurrentRow();
    currentRow.value = '';
  } else {
    currentRow.value = val;
    patrolRecordTrackPointApi(val);
  }
};

// 清除图层数据
const CLEAR_MAP_LAYER = () => {
  REMOVE_MAP_IMG('point-dot');
  REMOVE_MAP_IMG('user-point-dot');
  CLEAR_POPUP_MAP();

  map?.getStyle()?.layers?.map((item) => {
    if (
      [
        'MEASURE_POINT',
        'MAP_LINE_LAYER',
        'MEASURE_POINT_C',
        'MAP_LINE_XH',
        'MAP_POINT_XH',
        'MAP_POINT_LAYER_LIGHT',
      ].includes(item?.metadata?.group) &&
      ['source'] in item
    ) {
      REMOVE_LAYER(item.id);
      REMOVE_MAP_IMG(item.id);
    }
  });

  map.setZoom(7);
};

// 查询属性信息
const getMapFeatures = () => {
  // 解除绑定需要加绑定的函数，不然无法解绑
  map.off('click', mapCallBack);

  map.on('click', mapCallBack);
};

// 地图点击查询
const mapCallBack = (e) => {
  const features = map.queryRenderedFeatures(e.point);

  vNodePopup = null;

  if (features.length && 'layerKey' in features[0].properties && features[0].properties.layerKey == '巡护轨迹') {
    console.info(features[0], features[0]?._geometry, features[0]?.geometry);

    if (features[0]?._geometry?.coordinates.length > 2 || features[0]?.geometry?.coordinates.length > 2) {
      features[0].properties['longitude'] =
        features[0]?._geometry?.coordinates[0][0] ?? features[0]?.geometry?.coordinates[0][0];
      features[0].properties['latitude'] =
        features[0]?._geometry?.coordinates[0][1] ?? features[0]?.geometry?.coordinates[0][1];
    } else {
      if ('item' in features[0].properties) {
        features[0].properties = {
          ...JSON.parse(features[0].properties.item),
        };
      }

      features[0].properties['longitude'] =
        features[0]?._geometry?.coordinates[0] ?? features[0]?.geometry?.coordinates[0];
      features[0].properties['latitude'] =
        features[0]?._geometry?.coordinates[1] ?? features[0]?._geometry?.coordinates[1];
    }

    vNodePopup = createVNode(CommonMapPopup, {
      popupInfo: features[0]?.properties,
      title: '巡护信息',
      mainLabel: ['巡护员:', '联系方式:', '管护站:', '巡护时长:', '巡护里程:', '巡护时间:', '是否达标:'],
      type: '巡护轨迹',
    });

    let elpopup = document.createElement('div');

    elpopup.className = 'popup_';
    elpopup.id = 'popup_id';
    render(vNodePopup, elpopup);

    MAP_POPUP(features, elpopup);
  }
};

// 查看
const handleLookInfo = (item) => {
  if (currentRow.value?.id !== item?.id) {
    CLEAR_MAP_LAYER();
    singleTableRef?.value?.setCurrentRow();
    currentRow.value = '';
  }

  if (Object.keys(lookItem.value).length && item?.id !== lookItem?.value.id) {
    mitt.emit('handleItemGJAll', true);

    CLEAR_MAP_LAYER();
    singleTableRef?.value?.setCurrentRow();
    currentRow.value = '';
  }

  lookItem.value = item;

  emit('handleRecordLookItem', item, true);
};

/*
 *@description: 分页查询巡护记录
 */
const recordPageListApi = () => {
  const data = [
    {
      id: 219,
      createdDate: '2024-01-05 17:01:14',
      createdBy: '56182170913492992',
      badgeNumber: null,
      startDate: '2024-01-05 16:58:36',
      endDate: '2024-01-05 17:01:13',
      trackLen: 559,
      patrolDuration: 157,
      track: null,
      gpx: {
        filename: '巡护轨迹_20240105165833.gpx',
        object: '56182170913492992/track/7928be9a70104ba6b54b311ae26e2f46.gpx',
        length: 4410,
      },
      upToStandard: true,
      creatorAccount: '18740305372',
      creatorAvatar: '56182170913492992/202309/7892f997fcb740d2825bb26bf972b17a.jpg',
      creatorName: '杨一',
      deptNames: ['林业站'],
    },
    {
      id: 218,
      createdDate: '2024-01-05 16:58:21',
      createdBy: '56182170913492992',
      badgeNumber: null,
      startDate: '2023-12-26 16:40:44',
      endDate: '2024-01-05 16:58:21',
      trackLen: 602,
      patrolDuration: 865056,
      track: null,
      gpx: {
        filename: '巡护轨迹_20231226164041.gpx',
        object: '56182170913492992/track/05c3293a26d94b8f86838520ddacce8d.gpx',
        length: 4765,
      },
      upToStandard: true,
      creatorAccount: '18740305372',
      creatorAvatar: '56182170913492992/202309/7892f997fcb740d2825bb26bf972b17a.jpg',
      creatorName: '杨一',
      deptNames: ['林业站'],
    },
    {
      id: 217,
      createdDate: '2023-12-26 16:39:49',
      createdBy: '56182170913492992',
      badgeNumber: null,
      startDate: '2023-12-26 16:34:04',
      endDate: '2023-12-26 16:39:45',
      trackLen: 1836,
      patrolDuration: 341,
      track: null,
      gpx: {
        filename: '巡护轨迹_20231226163401.gpx',
        object: '56182170913492992/track/a776a1c51a044caeac0f4b6cadd0ec92.gpx',
        length: 7583,
      },
      upToStandard: true,
      creatorAccount: '18740305372',
      creatorAvatar: '56182170913492992/202309/7892f997fcb740d2825bb26bf972b17a.jpg',
      creatorName: '杨一',
      deptNames: ['林业站'],
    },

    {
      id: 206,
      createdDate: '2023-11-24 10:31:25',
      createdBy: '52952154230702080',
      badgeNumber: null,
      startDate: '2023-11-24 10:31:18',
      endDate: '2023-11-24 10:31:20',
      trackLen: 17,
      patrolDuration: 1,
      track: null,
      gpx: {
        filename: '巡护轨迹_20231124103115.gpx',
        object: '52952154230702080/track/c25040a43b554670b81495e88ffd5e2d.gpx',
        length: 785,
      },
      upToStandard: false,
      creatorAccount: '15877480107',
      creatorAvatar: '52952154230702080/202311/dd52bf3c04a744efb87e7d4baa01513b.jpg',
      creatorName: '菲F',
      deptNames: ['图灵普惠', '积木科技', '林业站', '东海道子管护站', '北家海子管护站', '三滩水管护站'],
    },
  ];

  for (let i = 0; i < data.length; i++) {
    const el = data[i];

    el['positionNames'] = el.deptNames.join('、');
  }

  tableList.value = data;
  total.value = 0;
};

/*
 *@description: 获取巡护记录的轨迹点
 */
const patrolRecordTrackPointApi = (item) => {
  const data = [
    {
      x: 108.90232958133343,
      y: 34.227208580199154,
      z: 'NaN',
      m: 'NaN',
    },
    {
      x: 108.90242958133344,
      y: 34.22730858019916,
      z: 'NaN',
      m: 'NaN',
    },
    {
      x: 108.90252958133344,
      y: 34.22740858019916,
      z: 'NaN',
      m: 'NaN',
    },
    {
      x: 108.90262958133344,
      y: 34.227508580199164,
      z: 'NaN',
      m: 'NaN',
    },
    {
      x: 108.90272958133345,
      y: 34.22760858019917,
      z: 'NaN',
      m: 'NaN',
    },
    {
      x: 108.90282958133345,
      y: 34.22770858019917,
      z: 'NaN',
      m: 'NaN',
    },
    {
      x: 108.90292958133345,
      y: 34.227808580199174,
      z: 'NaN',
      m: 'NaN',
    },
    {
      x: 108.90302958133346,
      y: 34.22790858019918,
      z: 'NaN',
      m: 'NaN',
    },
    {
      x: 108.90312958133346,
      y: 34.22800858019918,
      z: 'NaN',
      m: 'NaN',
    },
    {
      x: 108.90322958133346,
      y: 34.228108580199184,
      z: 'NaN',
      m: 'NaN',
    },
    {
      x: 108.90332958133347,
      y: 34.22820858019919,
      z: 'NaN',
      m: 'NaN',
    },
    {
      x: 108.90342958133347,
      y: 34.22830858019919,
      z: 'NaN',
      m: 'NaN',
    },
    {
      x: 108.90352958133347,
      y: 34.22840858019919,
      z: 'NaN',
      m: 'NaN',
    },
    {
      x: 108.90362958133348,
      y: 34.2285085801992,
      z: 'NaN',
      m: 'NaN',
    },
    {
      x: 108.90372958133348,
      y: 34.2286085801992,
      z: 'NaN',
      m: 'NaN',
    },
    {
      x: 108.90382958133348,
      y: 34.2287085801992,
      z: 'NaN',
      m: 'NaN',
    },
    {
      x: 108.90392958133349,
      y: 34.22880858019921,
      z: 'NaN',
      m: 'NaN',
    },
    {
      x: 108.90402958133349,
      y: 34.22890858019921,
      z: 'NaN',
      m: 'NaN',
    },
    {
      x: 108.90412958133349,
      y: 34.22900858019921,
      z: 'NaN',
      m: 'NaN',
    },
    {
      x: 108.9042295813335,
      y: 34.22910858019922,
      z: 'NaN',
      m: 'NaN',
    },
    {
      x: 108.9043295813335,
      y: 34.22920858019922,
      z: 'NaN',
      m: 'NaN',
    },
    {
      x: 108.9044295813335,
      y: 34.22930858019922,
      z: 'NaN',
      m: 'NaN',
    },
    {
      x: 108.9045295813335,
      y: 34.22940858019923,
      z: 'NaN',
      m: 'NaN',
    },
    {
      x: 108.90462958133351,
      y: 34.22950858019923,
      z: 'NaN',
      m: 'NaN',
    },
    {
      x: 108.90472958133351,
      y: 34.22960858019923,
      z: 'NaN',
      m: 'NaN',
    },
    {
      x: 108.90482958133352,
      y: 34.22970858019924,
      z: 'NaN',
      m: 'NaN',
    },
    {
      x: 108.90492958133352,
      y: 34.22980858019924,
      z: 'NaN',
      m: 'NaN',
    },
    {
      x: 108.90502958133352,
      y: 34.22990858019924,
      z: 'NaN',
      m: 'NaN',
    },
    {
      x: 108.90512958133353,
      y: 34.23000858019925,
      z: 'NaN',
      m: 'NaN',
    },
    {
      x: 108.90522958133353,
      y: 34.23010858019925,
      z: 'NaN',
      m: 'NaN',
    },
    {
      x: 108.90532958133353,
      y: 34.23020858019925,
      z: 'NaN',
      m: 'NaN',
    },
    {
      x: 108.90542958133354,
      y: 34.23030858019926,
      z: 'NaN',
      m: 'NaN',
    },
    {
      x: 108.90552958133354,
      y: 34.23040858019926,
      z: 'NaN',
      m: 'NaN',
    },
  ];

  if (data.length) {
    userItemLayer.startPoint = {
      longitude: data[0].x,
      latitude: data[0].y,
      id: 1,
    };
    userItemLayer.endPoint = {
      longitude: data[data.length - 1].x,
      latitude: data[data.length - 1].y,
      id_: 2,
      ...item,
    };

    const lineArr = [];

    for (let i = 0; i < data.length; i++) {
      const el = data[i];
      let pointItem = [];

      pointItem = [el.x, el.y];

      lineArr.push(pointItem);
    }

    userItemLayer.line = turf.lineString(lineArr, { ...item, layerKey: '巡护轨迹' });

    POINT_MARKER(userItemLayer.startPoint, '巡护轨迹', item, layerGroupId.MEASURE_POINT, 'point-dot');

    setTimeout(() => {
      MAP_UPDATE_REALTIME_LINE(
        userItemLayer.line,
        userItemLayer,
        layerGroupId.MAP_LINE_LAYER,
        layerGroupId.MAP_POINT_LAYER_LIGHT,
      );
      getMapFeatures();
    }, 1);
  }
};

onBeforeUnmount(() => {
  CLEAR_MAP_LAYER();
  map.off('click', mapCallBack);
  vNodePopup = null;
});
</script>

<template>
  <div class="record_root_gj">
    <div class="select_">
      <div>
        <p>管护单位</p>
        <ElSelect
          v-model="selectParams.deptName"
          placeholder="请选择管护单位"
          clearable
          @change="(e) => onChangeOption(e)"
        >
          <ElOption v-for="item in patrolOption" :key="item.id" :label="item.roleName" :value="item.id" />
        </ElSelect>
      </div>
      <div>
        <p>截止日期</p>
        <ElDatePicker
          v-model="selectParams.dateRange"
          type="daterange"
          range-separator="——"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          @change="onChangeDataRange"
        />
      </div>
      <div>
        <p>人员姓名</p>
        <ElInput v-model.trim="selectParams.username" placeholder="请输入" maxlength="22" />
        <ElButton type="primary" class="qr_" @click="handleSelectQuery()">确认</ElButton>
      </div>
    </div>
    <div class="table_main table_">
      <ElTable
        ref="singleTableRef"
        :data="tableList"
        :header-cell-style="{
          color: '#D0F2FF',
          background: 'rgba(25, 66, 117,0.4)',
        }"
        class="table_border"
        :highlight-current-row="true"
        @row-click="handleRowClick"
      >
        <ElTableColumn type="index" label="序号" align="center" width="55" />

        <ElTableColumn prop="creatorName" label="巡护人员" align="center" width="105">
          <template #default="scope">
            <p class="content_style style_c" :title="scope.row.creatorName">
              <img :src="PATROL_ICON" /><span>{{ scope.row.creatorName }}</span>
            </p>
          </template>
        </ElTableColumn>
        <ElTableColumn prop="trackLen" label="里程(km)" align="center" width="95">
          <template #default="scope">
            <span class="content_style">{{ (scope.row.trackLen * 0.001).toFixed(2) }}</span>
          </template>
        </ElTableColumn>
        <ElTableColumn prop="startDate" label="起止时间" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span class="content_style" :title="`${scope.row.startDate}-${scope.row.endDate.split(' ')[1]}`">{{
              scope.row.startDate.split(' ')[0]
            }}</span>
          </template>
        </ElTableColumn>
        <ElTableColumn label="操作" align="center" width="60">
          <template #default="scope">
            <div
              class="edit_btn"
              :style="{ color: lookState && lookItem?.id == scope.row?.id ? '#ffffff !important' : '' }"
              @click.stop="handleLookInfo(scope.row)"
            >
              查看
            </div>
          </template>
        </ElTableColumn>
      </ElTable>
    </div>
    <div class="pagination_style">
      <ElPagination
        v-model:currentPage="selectParams.pageNum"
        v-model:page-size="selectParams.pageSize"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="prev, pager, next, "
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<style scoped lang="scss">
.record_root_gj {
  position: relative;
  height: 100%;
  .select_ {
    margin-top: 21px;
    div {
      display: flex;
      align-items: center;
      margin-bottom: 8px;
      p {
        width: 80px;
        margin-right: 12px;
        text-align: right;
      }
      .qr_ {
        margin-bottom: 6px;
        margin-left: 14px;
      }
    }

    :deep(.el-input) {
      width: 286px;
    }
    :deep(.el-input__inner) {
      color: #d0f2ff;
    }
    :deep(.el-date-editor .el-range-input) {
      color: #d0f2ff;
    }
    :deep(.el-input__wrapper) {
      background: none;
      box-shadow: 0 0 0 0.0625rem rgba(228, 228, 228, 0.2) inset;
    }
    :deep(.el-select) {
      width: 80%;
    }
  }
  .table_main {
    .style_c {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      color: #d0f2ff;
      font-size: 16px;
      span {
        display: inline-block;
        width: 67px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
      }
    }
    .content_style {
      color: #d0f2ff;
      font-size: 16px;
    }

    .img_style {
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .table_border {
      width: 100%;
      height: 480px;
      border-radius: 4px;
    }

    .point_icon {
      .el-icon {
        color: #66bbfd;
        font-size: 18px;
        cursor: pointer;
        &:hover {
          color: #ffffff;
        }
      }
      .point_true {
        color: #ffffff !important;
      }
    }

    .edit_btn {
      color: #d0f2ff !important;
      cursor: pointer;
    }

    :deep(.el-table td.el-table__cell div) {
      color: #fff;
    }
    :deep(.el-table) {
      background: rgba(25, 66, 117, 0.2) !important;
    }
    :deep(.el-table__empty-text) {
      color: #ffffff !important;
    }

    :deep(.el-table) {
      --el-table-border-color: rgba(25, 66, 117, 0.1) !important
      ;
    }
    :deep(.el-table__column-filter-trigger i) {
      color: #ffffff !important;
      font-size: 18px;
    }

    :deep(.el-table__body tr.current-row > td.el-table__cell) {
      background-color: rgba(140, 182, 255, 0.3) !important;
    }

    :deep(.el-table tr) {
      font-size: 16px;
      background: none !important;
    }
    :deep(tr:hover > td) {
      background-color: rgba(25, 66, 117, 0.6) !important;
    }
  }
  .pagination_style {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
    :deep(.el-icon) {
      font-size: 16px !important;
    }

    :deep(.el-pagination button) {
      color: #ffffff;
      background: rgba(24, 33, 47, 0.56);
      border-color: #ffffff1f;
    }

    :deep(.el-pagination .el-pager li) {
      color: #ffffff;
      font-size: 16px;
      background: #ffffff1f;
    }

    :deep(.el-pagination .el-pager li.is-active) {
      width: 40px;
      height: 40px;
      color: #669eff;
      background: rgba(24, 33, 47, 0.56);
      border: 1px solid #669eff;
      border-radius: 4px;
    }
  }
}
</style>
